# -*- coding: utf-8 -*-

# Create your views here.
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect

from ..models import (
    ItemsRemitos,
    Remitos,
    Remates,
    ItemsRemates,
)
from ..forms import (
    RemateForm,
    ItemsRemateForm,
    VenderForm,
)


# REMATES

def listado_remates(request):
    """Listado de remates"""
    if request.user.is_authenticated():
        todo = Remates.objects.all()
        variables = RequestContext(request, {
            'todo': todo,
        })
        return render_to_response('listado_remates.html', variables)
    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)


def agregar_remates(request):
    """Agrega un remate nuevo"""
    if request.user.is_authenticated():
        if request.method == 'POST':
            form = RemateForm(request.POST)
            if form.is_valid():
                registro = form.save()
                return HttpResponseRedirect('/remates/listado/items/%s/' % registro.id)
        else:
            form = RemateForm()
        variables = RequestContext(request, {
            'form': form,
        })
        return render_to_response('agregar_remates.html', variables)
    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)


def editar_remates(request, remateid):
    """Edita remate"""
    if request.user.is_authenticated():
        r = Remates.objects.get(pk=remateid)
        if request.method == 'POST':
            form = RemateForm(request.POST, instance=r)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect('/remates/listado/')
        else:
            form = RemateForm(instance=r)
        variables = RequestContext(request, {'form': form})
        return render_to_response('editar_remates.html', variables)
    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)


def listado_items_remates(request, remateid):
    """Listado de items del remate"""
    if request.user.is_authenticated():
        remate = Remates.objects.get(pk=remateid)
        registro = None
        error = None
        if request.method == 'POST':
            form = ItemsRemateForm(request.POST)
            if form.is_valid():
                remito = form.cleaned_data['numeroRemito']
                linea = form.cleaned_data['numeroLinea']
                try:
                    r = Remitos.objects.get(numeroRemito=remito)
                    registro = ItemsRemitos.objects.get(remito=r, numeroLinea=linea)
                except:
                    error = 'No existe el remito ingresado.'
                todo = ItemsRemates.objects.filter(remate=remate).order_by('id')
                variables = RequestContext(request, {
                    'form': form,
                    'todo': todo,
                    'remate': remate,
                    'registro': registro,
                    'error': error,
                })
                return render_to_response('listado_itemsRemates.html', variables)
        else:
            form = ItemsRemateForm()
        todo = ItemsRemates.objects.filter(remate=remate).order_by('id')
        variables = RequestContext(request, {
            'form': form,
            'todo': todo,
            'remate': remate,
        })
        return render_to_response('listado_itemsRemates.html', variables)
    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)


def agregar_items_remates(request, remateid, articuloid):
    """Agrega un item de remate nuevo"""
    rem = Remates.objects.get(pk=remateid)
    art = ItemsRemitos.objects.get(pk=articuloid)
    todo = ItemsRemates.objects.filter(remate=rem).order_by('-id')
    if len(todo) == 0:
        lote = 1
    else:
        lote = todo[0].numeroLote + 1
    if request.POST:
        item = ItemsRemates(remate=rem, articulo=art, numeroLote=lote, precioVenta=None, detalle=None, comprador=None,
                            vendido=False)
        item.save()
    form = ItemsRemateForm()
    registro = None
    todo = ItemsRemates.objects.filter(remate=rem)
    variables = RequestContext(request, {
        'form': form,
        'todo': todo,
        'remate': rem,
        'registro': registro,
    })
    return render_to_response('listado_itemsRemates.html', variables)


def check_items_remates(request, itemid):
    """Confirmar antes de eliminar"""
    if request.user.is_authenticated():
        item = ItemsRemates.objects.get(pk=itemid)
        variables = RequestContext(request, {'item': item})
        return render_to_response('borrado_itemsRemates.html', variables)
    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)


def borrar_items_remates(request, itemid):
    """Elimina Banco dolares"""
    if request.user.is_authenticated():
        r = ItemsRemates.objects.get(pk=itemid)
        remateid = r.remate.id
        r.delete()
        return HttpResponseRedirect('/remates/listado/items/%s/' % remateid)
    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)


def vender_items_remates(request, itemid):
    """Vender item"""
    if request.user.is_authenticated():
        item = ItemsRemates.objects.get(pk=itemid)
        if request.method == 'POST':
            form = VenderForm(request.POST, instance=item)
            if form.is_valid():
                registro = form.save()
                registro.vendido = True
                registro.save()
                return HttpResponseRedirect('/remates/listado/items/%s/' % (item.remate.id))
            else:
                return HttpResponseRedirect('/remates/listado/items/%s/' % (item.remate.id))
        else:
            form = VenderForm(instance=item)
        variables = RequestContext(request, {
            'form': form,
            'item': item,
        })
        return render_to_response('vender_itemsRemates.html', variables)
    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)


def listado_items_remates_vendidos(request, remateid):
    """Listado de items del remate vendidos"""
    if request.user.is_authenticated():
        remate = Remates.objects.get(pk=remateid)
        todo = ItemsRemates.objects.filter(remate=remate, vendido=True)
        variables = RequestContext(request, {
            'todo': todo,
            'remate': remate,
        })
        return render_to_response('listado_itemsRemates_vendidos.html', variables)
    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)
